/******************************************************************************
** 
** Vertical histogramm.
** 
** File name:	word_lengths_vhistogramm.c
** Compilation:	cc word_lengths_vhistogramm.c -o word_lengths_vhistogramm
** Execution:	./word_lengths_vhistogramm
** 
** Description:
** Reads the input and prints the vertical histogramm of word's lengths 
** frequencies. "Word" consists of symbols 'a'-'z', 'A'-'Z' and '0'-'9'.
** 
******************************************************************************/
#include <stdio.h>

#define IN 1
#define OUT 0
#define H_MAX_HEIGHT 30     // histogramm's column maximum height
#define H_ELEMENT "#"       // element which forms a histogramm column
#define W_MAX_LENGTH 10     // maximum length of the word treated as separate in the histogramm

int c, i, j, state, nletters;
int lengths[W_MAX_LENGTH+1]; // lengths[0] is for words that are longer than W_MAX_LENGTH letters
float most_frequent_length;

main()
{
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      lengths[i]=0;
    }
    state = OUT;
    nletters = 0;
    
    // reading the input, counting words' lengths in the lengths[] array
    while ((c=getchar()) != EOF) {
      if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
        if (state == OUT) {
          state = IN;
          nletters=1;
        } else {
          ++nletters;
        }
      } else {
        if (state == IN) {
          state = OUT;
          if (nletters <= W_MAX_LENGTH) {
            ++lengths[nletters];
          } else {
            ++lengths[0];
          }
          nletters = 0;
        }
      }
    }
    
    // defining the most frequent word length
    most_frequent_length = 0;
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      if (most_frequent_length < lengths[i]) {
        most_frequent_length = lengths[i];
      }
    }

    // printing the histogramm
    printf("\n");
    for (i=H_MAX_HEIGHT; i>=0; --i) {
    if (i==H_MAX_HEIGHT) {
      printf("%5.0f", most_frequent_length);
    } else if (i==0) {
      printf("%5d", 0);
    } else {
      printf("%5s", " ");
    }
      for (j=0; j<=W_MAX_LENGTH; ++j) {
        if ((lengths[j]/most_frequent_length*H_MAX_HEIGHT) >= i) {
          printf("%3s", H_ELEMENT);
        } else {
          printf("%3s", " ");
        }
      }
      printf("\n");
    }
    printf("%5s", " ");
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      if(i==0) {
        printf(">%2d", W_MAX_LENGTH);
      } else {
        printf("%3d", i);
      }
    }
    printf("\n");
}

